import html2canvas from 'html2canvas'

/**
 * 根据图片的url转换对应的base64值
 * @param { String } imageUrl 如：http://xxxx/xxx.png
 * @returns base64取值
 */
export const urlToBase64 = (imageUrl: string): any => {
  return new Promise((resolve, reject) => {
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    const img = new Image()
    img.crossOrigin = '*' // 解决Canvas.toDataURL 图片跨域问题
    img.src = imageUrl
    img.onload = () => {
      canvas!.height = img.height
      canvas!.width = img.width
      ctx!.fillStyle = '#fff' // canvas背景填充颜色默认为黑色
      ctx!.fillRect(0, 0, img.width, img.height)
      ctx!.drawImage(img, 0, 0) // 参数可自定义
      const dataURL = canvas.toDataURL('image/png') // 获取Base64编码
      resolve(dataURL)
      canvas.remove() // 清除canvas元素
      img.remove() // 清除img元素
    }
    img.onerror = () => {
      reject(new Error('Could not load image at ' + imageUrl))
    }
  })
}

/**
 * 下载Base64图片到本地
 * @param {*} content base64
 * @param {*} fileName 下载文件名
 */
export const downloadBase64Img = (content: any, fileName?: string) => {
  const base64ToBlob = function (code: string) {
    const parts = code.split(';base64,')
    const contentType = parts[0].split(':')[1]
    const raw = window.atob(parts[1])
    const rawLength = raw.length
    const uInt8Array = new Uint8Array(rawLength)
    for (let i = 0; i < rawLength; ++i) {
      uInt8Array[i] = raw.charCodeAt(i)
    }
    return new Blob([uInt8Array], {
      type: contentType
    })
  }
  const aLink = document.createElement('a')
  const blob = base64ToBlob(content) //new Blob([content]);
  const date = new Date().getTime()
  aLink.download = fileName || date + '.png'
  aLink.href = URL.createObjectURL(blob)
  aLink.click()
}

export const download = (url: string, name?: string) => {
  const link = document.createElement('a')
  link.href = url
  link.download = name || url // 设置下载文件的名称
  link.style.display = 'none'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

export const downloadImg = (url: string, name?: string) => {
  try {
    const image = new Image()
    // 解决跨域 canvas污染问题
    image.setAttribute('crossOrigin', 'anonymous')
    image.src = `${url}?time=${new Date().valueOf()}` // 加时间戳
    setTimeout(() => {
      image.onload = () => {
        const canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        const context: any = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height)
        canvas.toBlob((blob: any) => {
          const href: any = URL.createObjectURL(blob)
          const a = document.createElement('a')
          const date = new Date().getTime()
          a.download = name || date + ''
          a.href = href
          a.click()
          a.remove()
          URL.revokeObjectURL(href)
        })
      }
    }, 10)
  } catch (e) {
    console.log('=============下载图片失败：', e)
    download(url)
  }
}

/**
 * 根据html Dom获取图片
 */
export const getImageByHtmlDom = (domId: any, width: any, height: any) => {
  return new Promise((resolve, reject) => {
    html2canvas(document.getElementById(domId) as any, {
      scale: 2, // 缩放比例,默认为1
      allowTaint: false, // 是否允许跨域图像污染画布
      useCORS: true, // 是否尝试使用CORS从服务器加载图像
      width: width || '500', // 画布的宽度
      height: height || '500', // 画布的高度
      backgroundColor: '#fff' // 画布的背景色，默认为透明
    })
      .then((canvas: any) => {
        // 将canvas转为base64格式，生成图片链接
        const imgUrl = canvas.toDataURL('image/png')
        resolve(imgUrl)
      })
      .catch((error: any) => {
        reject(error)
      })
  })
}
